/*
*	var follow = require("./follow");
*   follow({"imgDomain":"","qrImgUrl":"","mpName":"mpName"});
*
*/
var parseModule = require("mlib/dom/parseModule");
var when = require("mlib/util/when");
var ajax = require("mlib/io/ajax");
var followRender = require("../ejs/follow.ejs");
var touch = require("mlib/evt/touch");

module.exports = function(codetype) {
    var nodeList = null; // 存储所有关键节点
	
	var m_html = null;
	var fragment = null;
	var div = null;
	var follow = null;
	var nodeList = null;
	var mpData = null;

	if(typeof(codetype)=="undefined"){
		codetype = 'subscribe';
	}
	getQrcode(codetype).then(getMpinfo).otherwise(function(msg) { 
		console.log("报错信息：" + msg);
	});

	function renderNode(data){
		m_html = followRender(data);
	    fragment = document.createDocumentFragment();
		div=document.createElement("div"); 
		div.insertAdjacentHTML('afterbegin', m_html);
		follow =div.firstElementChild;
		document.body.appendChild(follow);
		fragment = div = null;
		nodeList = parseModule(follow);
		bindEvent();
	}

	function bindEvent(){
		touch.on(nodeList.fork, "tap", removeFollow);
	}

	function getMpinfo(result){		
		var resdata = result.data;
				mpData = {
					"textcase":result.type=="voucher" ? "获取凭证" : "关注公众号",
					"qrImgUrl":resdata.ticketUrl,
					"mpName":resdata.publicname
				};
				renderNode(mpData);
	}

	function getQrcode(type){
		var apiurl  = null;
		switch(type){
			case 'voucher':
				apiurl = '/index.php?r=CouponApi/data/wechat&type=1';
				break;
			case 'subscribe':
				apiurl = '/index.php?r=CouponApi/data/wechat&type=2';
				break;
		}
		var defer = when.defer();
		ajax({ 
			url: apiurl,
			onSuccess: function(result) {	
			    result.type = codetype;			
			    defer.resolve(result);
			},
			onError: function(xmlHttp) {
				 that.unLock();
			}
		});
		return defer.promise;

	}
	function removeFollow(){
		//touch.off( nodeList.fork, "tap", removeFollow);
		follow.remove();
	}		
}

